package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.BehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleBehaviorDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: Luo Zeqi
 * @Date: 2022/11/17/9:49
 */
@Service
@Slf4j
@Transactional
public class BehaviorServiceImpl implements BehaviorService {

    @Autowired
    private CacheService cacheService;

    /**
     * 收藏/取消收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {

        try {
            if (!StringUtils.isEmpty(dto.getEntryId())) {
                if (dto.getOperation() == 0) {
                    //收藏
                    //当前用户id+行为类型作为key、文章id作为hashkey,dto作为value
                    String key = "COLLECTION_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/; //后端测试已通，需放开后联调
                    String hashkey = String.valueOf(dto.getEntryId());
                    String jsonString = JSON.toJSONString(dto);

                    cacheService.hPutIfAbsent(key, hashkey, jsonString);

                } else if (dto.getOperation() == 1) {
                    //取消收藏
                    String key = "COLLECTION_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/;
                    String hashkey = String.valueOf(dto.getEntryId());

                    cacheService.hDelete(key, hashkey);
                }
            } else {
                log.info("收藏参数错误");
                throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
            }
        } catch (Exception e) {
            log.info("收藏操作失败：{}", e);
            return ResponseResult.errorResult(500, "操作失败");
        }

        return ResponseResult.okResult("操作成功");
    }

    /**
     * 用户行为的数据回显
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        ArticleBehaviorDto articleBehaviorDto = new ArticleBehaviorDto();
        try {
            if (!StringUtils.isEmpty(dto.getArticleId()) && !StringUtils.isEmpty(dto.getAuthorId())) {

                //当前用户id+行为类型作为key、文章id作为hashkey, 获取redis中的行为信息
                //封装数据
                //1.查询是否点赞
                String keyLike = "LIKE_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/; //后端测试已通，需放开后联调
                String hashkey = String.valueOf(dto.getArticleId());
                Object jsonLikeStr = cacheService.hGet(keyLike, hashkey);
                if (jsonLikeStr == null) {
                    //redis中不存在，则就是没有对该文章点赞
                    articleBehaviorDto.setIslike(false);
                }else {
                    //已点赞
                    LikesBehaviorDto likesBehaviorDto = JSON.parseObject(String.valueOf(jsonLikeStr), LikesBehaviorDto.class);
                    //判断是否是文章点赞
                    if (likesBehaviorDto.getOperation() == 0 && likesBehaviorDto.getType() == 0){
                        articleBehaviorDto.setIslike(true);
                    }else {
                        log.info("不是文章点赞类型");
                        articleBehaviorDto.setIslike(false);
                    }
                }

                //2.查询阅读数量
                String keyCount = "READ_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/; //后端测试已通，需放开后联调
                Object jsonCountStr = cacheService.hGet(keyCount, hashkey);
                if (jsonCountStr == null) {
                    //redis中不存在，则就是第一次点开该文章
                    articleBehaviorDto.setCount(0);
                }else {
                    //获取点击数
                    ReadBehaviorDto readBehaviorDto = JSON.parseObject(String.valueOf(jsonCountStr), ReadBehaviorDto.class);
                    articleBehaviorDto.setCount(readBehaviorDto.getCount());
                }


                //3.查询是否不喜欢
                String keyUnLike = "UN_LIKE_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/; //后端测试已通，需放开后联调
                Object jsonUnlikeStr = cacheService.hGet(keyUnLike, hashkey);
                if (jsonUnlikeStr == null) {
                    //redis中不存在，则就是没有不喜欢该文章
                    articleBehaviorDto.setIsunLike(false);
                }else {
                    //不喜欢
                    UnLikesBehaviorDto unLikesBehaviorDto = JSON.parseObject(String.valueOf(jsonUnlikeStr), UnLikesBehaviorDto.class);
                    //判断类型是否对应
                    if (unLikesBehaviorDto.getType() == 0){
                        articleBehaviorDto.setIsunLike(true);
                    }else {
                        log.info("数据有误");
                        throw new CustomException(AppHttpCodeEnum.DATA_ERROR);
                    }
                }

                //4.查询是否收藏
                String keyCollection = "COLLECTION_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/; //后端测试已通，需放开后联调
                Object jsonCollectionStr = cacheService.hGet(keyCollection, hashkey);
                if (jsonCollectionStr == null) {
                    //redis中不存在，则就是没有收藏该文章
                    articleBehaviorDto.setIscollection(false);
                }else {
                    //收藏
                    CollectionBehaviorDto collectionBehaviorDto = JSON.parseObject(String.valueOf(jsonCollectionStr), CollectionBehaviorDto.class);
                    //判断是否是文章收藏
                    if (collectionBehaviorDto.getType() == 0){
                        articleBehaviorDto.setIscollection(true);
                    }else {
                        log.info("不是文章收藏");
                        throw new CustomException(AppHttpCodeEnum.DATA_ERROR);
                    }
                }


                //5.查询是否关注作者
                String keyFollow = "FOLLOW_BEHAVIOR_" /*+ ApUserThreadLocalUtil.get().getId().intValue()*/; //后端测试已通，需放开后联调
                Object jsonFollowStr = cacheService.hGet(keyFollow, hashkey);
                if (jsonFollowStr == null) {
                    //redis中不存在，则就是没有关注文章的作者
                    articleBehaviorDto.setIsfollow(false);
                }else {
                    //收藏
                    UserRelationDto userRelationDto = JSON.parseObject(String.valueOf(jsonFollowStr), UserRelationDto.class);
                    //判断作者id是否对应上
                    if (userRelationDto.getAuthorId() == dto.getAuthorId()){
                        articleBehaviorDto.setIsfollow(true);
                    }else {
                        log.info("作者id和redis中存的不一致");
                        articleBehaviorDto.setIsfollow(false);
                    }
                }

            } else {
                log.info("行为数据回显参数错误");
                throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
            }
        } catch (Exception e) {
            log.info("行为数据回显操作失败：{}", e);
            return ResponseResult.errorResult(500, "操作失败");
        }

        //返回数据
//        String jsonString = JSON.toJSONString(articleBehaviorDto);//这不能转为字符串传输
        return ResponseResult.okResult(articleBehaviorDto);
    }
}
